package com.fingard.dsp.bank.directbank.wfccb01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.directbank.fngrd01.util.StringHelper;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.util.Calendar;
import java.util.Date;

/**
 * 潍坊银行明细查询
 * Created by F on 2019/06/17.
 */
public class WFCCB01Transaction extends WFCCB01Base implements ITransaction {
    /**
     * 历史明细
     * @param p_req7516
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception{
        RetAtsTrans retAtsTrans = new RetAtsTrans(p_req7516.reqHeader);
        retAtsTrans.writeStart();
        String tmpRespCode = "";
        String tmpRespInfo ="";
        try{
            //起始日期
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());
            //结束日期
            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            while(tmpIntDateFrom<=tmpIntDateTo && StringHelper.isNullOrEmpty(tmpRespCode)){
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                //当是跨月查询时，先查询起始日期到月末日期记录，再查询月末后一天日期到结束日期记录
                if(DateHelper.compareMonth(tmpCalendarFrom,tmpCalendarTo)==-1){
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH,tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                }else{
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }
                //======拼接报文======
                //拼接请求报文体
                WFCCB01Header header = new WFCCB01Header();
                header.opname="queryAccHisDetail";
                header.serialNo = getQryTransID();
                XmlTextWriter xmlReq = new XmlTextWriter();
                writeReqHeader(xmlReq,header);
                XElement body =new XElement("ReqParam","");
                body.addChild(new XElement("accountNo",p_req7516.actNum));//账号
                body.addChild(new XElement("beginDate",Format.Date8Format.format(tmpCalendarFrom.getTime())));//开始时间
                body.addChild(new XElement("endDate",Format.Date8Format.format(tmpClndrStepTo.getTime())));//结束时间
                xmlReq.writeXElement(body);
                xmlReq.writeEndDocument();
                //获取签名数据
                String sign=signnatrue(xmlReq.toXmlString());
                //拼接请求报文
                XmlTextWriter xmlTextWriter = new XmlTextWriter();
                header.signedData=sign;
                writeCommonHeader(xmlTextWriter,header);
                xmlTextWriter.directWrite(xmlReq.toXmlString());
                xmlTextWriter.writeEndElement();
                //======拼接报文======
                //发送请求报文
                String[] resutlt = sendToBank(requestBody(header,xmlTextWriter.toXmlString()));
                //处理响应报文
                if(resutlt[0].length()==0){
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(resutlt[1], tmpSbMsg);
                        if(tmpBkReader!=null) {
                            String respCode = tmpBkReader.getFirstText("/BankData/opRep/hostReturnCode");
                            String respInfo = tmpBkReader.getFirstText("/BankData/opRep/hostErrorMessage");
                            if (success(respCode)) {//交易成功
                                int totalNum=Integer.parseInt(tmpBkReader.getFirstText("/BankData/opRep/turnPageTotalNum"));//总数
                                WriteBankLogLn("查询明细总数为："+totalNum);
                                if(totalNum>0){
                                    int count=0;
                                    while (tmpBkReader.read("/BankData/opRep/RepParam/tranDetail/row")){
                                        XElement readXElement = tmpBkReader.readedXElement;
                                        RetAtsTransDetail detail = new RetAtsTransDetail();
                                        detail.actArea=p_req7516.actArea;
                                        detail.actNum = p_req7516.actNum;
                                        detail.tranDate =DateHelper.convertD8toD10(readXElement.getSingleTextNotNull("transferDate").trim());
                                        detail.valueDate = detail.tranDate;
                                        String times=readXElement.getSingleTextNotNull("transferTime").trim();
                                        detail.tranTime = detail.valueDate+ " " + times.substring(0,2)+":"+times.substring(2,4)+":"+times.substring(4,6);
                                        detail.cur = convertCurToATS(readXElement.getSingleTextNotNull("currencyType").trim());//币种
                                        detail.accBal = delZero(readXElement.getSingleTextNotNull("balance"));//账户余额
                                        String note = readXElement.getSingleTextNotNull("rem").trim();
                                        detail.usage = note;
                                        detail.abstr = pickupAbstr(note);
                                        detail.originator = readXElement.getSingleTextNotNull("transferFlowNo").trim();//银行流水号
                                        detail.recAccNum = readXElement.getSingleTextNotNull("account").trim();
                                        detail.recAccName = readXElement.getSingleTextNotNull("accountName").trim();
                                        detail.recAccBank = readXElement.getSingleTextNotNull("accountBankNo").trim();
                                        String payAmount=readXElement.getSingleTextNotNull("payAmount");
                                        String recAmount=readXElement.getSingleTextNotNull("recAmount");
                                        if(!delZero(payAmount.replaceAll("A","")).equals("0.00")){
                                            if(payAmount.contains("A")){
                                                detail.cdFlag="2";
                                                detail.tranAmt=delZero(payAmount.replaceAll("A",""));
                                            }else {
                                                detail.cdFlag="1";
                                                detail.tranAmt=delZero(payAmount);
                                            }
                                        }else if(!delZero(recAmount.replaceAll("A","")).equals("0.00")){
                                            if(recAmount.contains("A")){
                                                detail.cdFlag="1";
                                                detail.tranAmt=delZero(recAmount.replaceAll("A",""));
                                            }else {
                                                detail.cdFlag="2";
                                                detail.tranAmt=delZero(recAmount);
                                            }
                                        }
                                        detail.comment = readXElement.getSingleTextNotNull("summary");
                                        retAtsTrans.writeRetDetail(detail);
                                        count++;
                                    }
                                    WriteBankLogLn("遍历数为："+count);
                                    if(totalNum!=count){
                                        WriteBankLogLn("返回总数与遍历数不一致，请检查");
                                    }
                                }
                            }else {//查询异常
                                tmpRespCode = "-1";
                                tmpRespInfo = respInfo;
                                break;
                            }
                        }else{
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpSbMsg.toString();
                        break;
                    }
                }else{
                    tmpRespCode = "-1";
                    tmpRespInfo = resutlt[1];
                    break;
                }
                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        }catch (Exception ex){
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            ex.printStackTrace();
            WriteBankLogLn("查询明细异常:"+ex);
        }
        if ("-1".equals(tmpRespCode)) {
            retAtsTrans = new RetAtsTrans(p_req7516.reqHeader);
            retAtsTrans.writeStart();//写返回ATS的统一头部信息
            retAtsTrans.writeRespCode(tmpRespCode);
            retAtsTrans.writeRespInfo(tmpRespInfo);
        }else if(retAtsTrans.getWrittenRdCount() == 0) {
            retAtsTrans.writeRespInfo("交易为空");
            retAtsTrans.writeRespCode("0");
        }
        retAtsTrans.writeEnd();
        return retAtsTrans;
    }

    /**
     * 今日明细
     * @param p_req7515
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception{
        Req7516HisTrans p_req7516 = new Req7516HisTrans(p_req7515.reqHeader);
        p_req7516.actArea = p_req7515.actArea;
        p_req7516.actCur = p_req7515.actCur;
        p_req7516.actNum = p_req7515.actNum;
        String date = Format.Date8Format.format(new Date());
        p_req7516.dateFrom = date;
        p_req7516.dateTo = date;
        return d_7516_HisTrans(p_req7516);
    }
}
